package thread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * ArrayList,LinkedList,HashSet,HashMap他们都不是并发安全的
 */
public class SyncApiDemo2 {
    public static void main(String[] args) {
//        List<Integer> list = new ArrayList<>();
//        List<Integer> list = new LinkedList<>();
        /*
            java.util.Collections
            该类提供了一套静态方法:synchronizedXXX,可以将现有的集合或Map转换为并发安全的
         */
        List<Integer> list = Collections.synchronizedList(new ArrayList<>());

        Thread t1 = new Thread(){
            public void run(){
                for (int i = 0; i < 1000; i++) {
                    list.add(i);
                }
            }
        };
        Thread t2 = new Thread(){
            public void run(){
                for (int i = 1000; i < 2000; i++) {
                    list.add(i);
                }
            }
        };
        t1.start();
        t2.start();

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        }

        System.out.println(list.size());
    }
}
